<?php

namespace App\Controller;
use Think\Controller;

/** 
 * [转盘活动]
 * @author Legend. <xcx_legender@qq.com>
 * @param 
 * @return 
 */
class TurntableController extends AppController
{
	
	protected $service 		= 'MallActivityTurntable';
	protected $service_obj  = null;

	protected $prizes = [
		1 => ['一等奖'],
		2 => ['二等奖'],
		3 => ['三等奖'],
		4 => ['四等奖'],
		5 => ['五等奖'],
	];

	var $testUids = [55, 54, 53, 3425, 86, 49, 76, 3473, 97, 3530];

	protected function _initialize()
	{
		parent::_initialize();
		$this->service_obj = service($this->service);
	}

	// 转盘活动的页面
	public function index($id = 0)
	{



		$data = $id ? $this->service_obj->info($id) : $this->service_obj->getLatest();
		
		if (!$data) return $this->display('over');

		$referral = I('referral', '', 'trim');
		$event = event('Activity');
		if ($referral)
		{
			// 通过推广给用户加活动次数
			$event->userRefer($this->service, 'share', $data, $referral, UID);
		}

		$this->assign('data', $data);
		// print_r($data);
		$times = 0;

		// 获取计算次数
		if (UID)
		{
			$total_times = $event->getUserDailyTimes($this->service, $data, UID);
			$times = $total_times - $this->getUserActionCount($data);

			$times = $times > 0 ? $times : 0;
		}
		// echo $times;
		$this->assign('times', $times);
		// print_r($this->user);
		$this->assign('user', $this->user);

		// 获取用户需要填写联系方式的进度
		$noContactPrize = $this->getUserNoContact($data);
		$set_contact = false;
		if ($noContactPrize)
		{
			$session = [
				'action_id' => $noContactPrize['id'],
				'prize'     => $noContactPrize['prize_level'].'p',
			];

			session('activity_turntable_useraction', $session);
			$set_contact = true;
			$this->assign('noContactPrize', $noContactPrize);
		}
		else
		{
			session('activity_turntable_useraction', null);
		}
		$this->assign('set_contact', (int) $set_contact);
		$test_uids = $this->testUids;
		if ( !UID || !in_array(UID, $test_uids))
		{
			return $this->display('Mall/await');
		}
		// print_r(get_defined_vars());
		
		$winners= $this->getLatestWinners($data);
		$Uevent = event('User');
		foreach ($winners as $key => &$winner) {
			$winner['user'] = $Uevent->info($winner['uid']);
			$winner['phone'] = substr_replace(get_username($winner['uid']),'****', 3,4);
			$winner['prize'] = $this->prizes[$winner['prize_level']][0];
		}
		$this->assign('winners', $winners);
		$this->display();
	}



	public function ajaxGetWinners($id = 0)
	{
		$data = $id ? $this->service_obj->info($id) : $this->service_obj->getLatest();
		$list = $this->getLatestWinners($data);
		$this->jsonList($list);
	}


	// 获得最新的中奖名单
	protected function getLatestWinners(&$data)
	{
		$map = [
			'object_id' 	=> (int) $data['id'],
			'prize_level'	=> ['lt', 6]
		];
		$list = service('Mall/TurntableUserAction')->where($map)->order('create_time desc')->limit(20)->select();
		return $list;
	}

	// 开始抽奖
	public function action()
	{
		$this->checkLogin();

		$event = event('Activity');

		$id = I('request.id', 0, 'intval');
		$data = $this->service_obj->info($id);
		// 判断活动状态
		$res = $event->checkStatus($this->service, $data);
		if (!$res)
		{
			return $this->error('该活动已经结束!');
		}

		// 判断是否需要将之前的联系方式给出
		$noContactPrize = $this->getUserNoContact($data);
		if ($noContactPrize) return $this->error('你上次的奖品还未填写联系信息, 请先填写');

		// 判断次数
		$total_times = $event->getUserDailyTimes($this->service, $data, UID);
		$times = $total_times - $this->getUserActionCount($data);
		if ($times <= 0)
		{
			return $this->error('您今日已经没有次数了, 请明日再来, 或分享获取更多次数');
		}

		// 获取抽奖结果
		$prize = $this->doAction($data);

		$action_id = $this->actionLog($data, $prize);
		$ret['prize'] = $prize;
		$ret['contact'] = in_array($prize, ['1', '2', '3']) ? 1 : 0;
		if ($ret['contact'])
		{
			$session = [
				'action_id' => $action_id,
				'prize'     => $prize,
			];
			session('activity_turntable_useraction', $session);
		}

		// 如果是4,5等奖则获取积分
		if (in_array($prize, [4,5]) )
		{
			$score = $prize == 4 ? 500 : 200;
			event('User')->score_oper(UID, $score, 'turntable', '轮盘抽奖', $data['id']);
		}

		return $this->success($ret);
	}

	// 填写联系方式
	public function contact()
	{
		$this->checkLogin();
		$session = session('activity_turntable_useraction');
		if (!$session)
		{
			return $this->error('您并没有中奖');
		}
		$name 		= I('name', '', 'trim');
		$phone 		= I('phone', '', 'trim');
		$address 	= I('address', '', 'trim');

		if (!$name || !$phone || !$address) return $this->error('请完善资料');
		$save['contact'] = compact('name', 'phone', 'address');
		$res = service('Mall/TurntableUserAction')->where(['id' => (int)$session['action_id']])->save($save);
		if ($res)
		{
			session('activity_turntable_useraction', null);
			return $this->success('操作成功');
		}
		return $this->error('操作失败');
	}

	protected function checkLogin()
	{
		if (!UID)
		{
			$this->json_login_error();
			exit;
		}
	}

	// 计算获得的奖品
	protected function doAction(&$data)
	{
		$temp_rates = 0;
		$prize_rates = [];

		$res = explode("\r\n", $data['prize']);
		foreach ($res as $key => $prize) {
			$level = $key + 1;
			list($rate, $limits) = explode("|", $prize);
			if ($limits)
			{
				list($key, $limit) = explode("=", $limits);
				if ($limit > 0)
				{
					$left = $this->getPrizeLeftCount($data, $level, $limit);
					if ($left <= 0) $rate = 0;
				}
			}
			$prize_rates[$level.'p'] = $rate;
			$temp_rates += $rate;
		}
		$prize_rates['6p'] = 1 - $temp_rates;
		$prize_bingo = mt_rand() / mt_getrandmax();
		
		$getPrize = '6p';

		$rate_ranger = 0;
		foreach ($prize_rates as $key => $value) {
			$rate_ranger += $value;
			if ($prize_bingo <= $rate_ranger) { $getPrize = $key; break;}
		}

		return intval($getPrize);
	}

	// 获取已经剩余的奖品数量
	protected function getPrizeLeftCount(&$data, $prize_level, $limit)
	{
		$map = [
			'object_id' 	=> (int) $data['id'],
			'prize_level'	=> (int) $prize_level,
		];
		$count = service('Mall/TurntableUserAction')->where($map)->count();
		return $limit - $count;
	}

	// 获取用户未填写联系方式的获奖信息
	protected function getUserNoContact(&$data)
	{
		$map = [
			'object_id' 	=> (int) $data['id'],
			'prize_level'	=> ['$in' => [1,2,3]],
			'uid'			=> UID,
			'contact'		=> null,
		];
		return service('Mall/TurntableUserAction')->where($map)->find();
	}

	// 记录用户抽奖行为
	protected function actionLog(&$data, $prize)
	{
		$save = [
			'uid' 			=> UID,
			'create_time' 	=> NOW_TIME,
			'date'   		=> date('Y-m-d'),
			'object_id' 	=> (int) $data['id'],
			'prize_level'	=> $prize
		];
		$_id = service('Mall/TurntableUserAction')->add($save);
		// $map = ['_id' => new \MongoId($_id)];
		// $data = service('Mall/TurntableUserAction')->where($map)->find();
		return $_id;
	}

	// 获取用户当日的使用次数
	protected function getUserActionCount(&$data)
	{
		$map = [
			'uid' 			=> UID,
			'date'   		=> date('Y-m-d'),
			'object_id' 	=> (int) $data['id'],
		];
		return service('Mall/TurntableUserAction')->where($map)->count();
	}

}